package logic

import (
	"context"
	"io"
	"net/http"

	"job/internal/svc"
	"job/proto"

	"github.com/zeromicro/go-zero/core/logx"
)

type CallbackLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackLogic {
	return &CallbackLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CallbackLogic) Callback(in *proto.JobRequest) (*proto.JobResponse, error) {
	// payload, _ := json.Marshal(in.Payload)
	var Code int64
	var Response string

	res, err := l.svcCtx.RequestService(l.ctx, in.Url, in.Payload)

	if err != nil {
		l.Error(err)
		return nil, err
	}

	if res.StatusCode == http.StatusAccepted {
		Code = 1
	}
	body, _ := io.ReadAll(res.Body)

	defer res.Body.Close()
	Response = string(body)

	return &proto.JobResponse{
		Code:     Code,
		Response: Response,
	}, nil
}
